import { getDataByCode } from '@/components/common/PateoForm/utils/helper';
import { getDicByKey } from '@/support/common';
import { LeftSquareFilled, PlusOutlined } from '@ant-design/icons';
import { Button, Card, Divider, Form, message, Select, Input, Space, Table } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import Ellipsis from '../../../components/Ellipsis';
import IPDADetailModal from '../../../components/ipda/ipdaDetailModal';
import TboxDetailModal from '../../../components/Tbox/tboxDetailModel';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import styles from './TableList.less';
import router from 'umi/router';
import { has, includes, isUndefined } from 'lodash';
import { getList } from '@/services/vehicle';
import { load } from '@amap/amap-jsapi-loader';


//分割线
let page = '';
const FormItem = Form.Item;
const { Option } = Select;
let typeMap = new Map();
let enrollMap = new Map();
let realMap = new Map();

const enrollStatusList = [
  { dataKey: 0, dataValue: '未激活' },
  { dataKey: 1, dataValue: '激活成功' },
  { dataKey: 2, dataValue: '激活失败' },
  { dataKey: 3, dataValue: '解除失败' },
];

const RealNameStatusList = [
  { dataKey: '0', dataValue: '未实名认证' },
  { dataKey: '1', dataValue: '认证中' },
  { dataKey: '2', dataValue: '实名认证通过' },
  { dataKey: '3', dataValue: '实名认证失败' },
  { dataKey: '4', dataValue: '解除申请中' },
  { dataKey: '5', dataValue: '实名认证解除成功' },
];

const searchAllList = [
  { dataKey: 1, dataValue: '用户车' },
  { dataKey: 2, dataValue: '试乘试驾车' },
  { dataKey: 3, dataValue: '展车' },
  { dataKey: 4, dataValue: '内部测试车' },
  { dataKey: 5, dataValue: '媒体车' },
  { dataKey: 6, dataValue: '质检车' },
  { dataKey: 9, dataValue: '试制车' },
];


class VehicleList extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };

  formRef = React.createRef();
  state = {
    redisData: {},
    tboxDetailVisible: false,
    ipdaDetailVisible: false,
    tboxDetailModelData: {},
    ipdaDetailModelData: {},
    formValues: {},
    data: '',
    detailDisable: false,
    typeSearchOptions: '',
    dealerActiveTypeOptions: '',
    enrollStatusOptions: [],
    realNameStatusOptions: [],
    data: [],
    loading: false,
    pagination: {},
  };

  componentWillMount() {
    this.props.dispatch({
      type: 'menu/getMenuData',
    })
    const { menu: { userProfile, dataPermission, permissions } } = this.props;

    const { dispatch } = this.props;

    this.setState({
      enrollStatusOptions: enrollStatusList.map(d => (
        <Option key={d.dataKey}>{d.dataValue}</Option>
      )),
      realNameStatusOptions: RealNameStatusList.map(d => (
        <Option key={d.dataKey}>{d.dataValue}</Option>
      )),
    });

    enrollStatusList.map(d => enrollMap.set(d.dataKey, d.dataValue));
    RealNameStatusList.map(d => realMap.set(d.dataKey, d.dataValue));
    searchAllList.map(d => typeMap.set(d.dataKey, d.dataValue));

    dispatch({
      type: 'qualityTest/options',
      payload: { url: '/groupManagement/getOption' },
    });
    dispatch({
      type: 'menu/getMenuData',
    });
  }
  componentDidMount() {
    const { menu: { dataPermission } } = this.props;
    const brandCodes = dataPermission.BRAND ? dataPermission.BRAND : []

    this.props.dispatch({
      type: 'basedata/redisDataFetch',
      callback: response => {
        if (response) {
          this.setState({ redisData: response });
        }
      },
    });
  };

  fetchData = (values) => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    this.setState({ loading: true });
    const params = {
      vin: values.vin || this.state.vin,
      page: values.current - 1 || undefined,
      size: values.pageSize || pagination.pageSize,
    };
    dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: '/vehicle/list',
        ...params,
      },
      callback: response => {
        if (response.statusCode === '0') {
          this.setState({
            data: response.data.list,
            pagination: {
              page: response.data.pagination.current,
              pageSize: response.data.pagination.pageSize,
              total: response.data.pagination.total
            },
            loading: false,
          });
        } else {
          message.error(response.statusMessage);
        }
      }
    });
  };

  // ToDo：查出多页，页面跳转有问题
  handleReset = () => {
    this.formRef.current.resetFields();
    this.setState({
      data: [],
      loading: false,
      vin: '',
      pagination: {},
    });
  };


  handleSearch = (vin) => {
    if (!isUndefined(vin.vin)) {
      this.setState({ vin: vin.vin });
      this.fetchData(vin);
    }
  };
  handleDetailTbox = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox/fetchtboxdetail',
      payload: deviceId,
      callback: tboxDetail => {
        this.setState({ tboxDetailModelData: tboxDetail.data, tboxDetailVisible: true });
      },
    });
  };

  //保存record信息  点击vin号跳转到 设备管理-车辆详情
  handleDetailVIN = deviceId => {
    // 先获取iccid信息
    this.props.dispatch({
      type: 'vehicle/getIccid',
      payload: deviceId.vin,
      callback: res => {
        if (res.statusCode === '0' && res.data.simProfileVo.iccid) {
          deviceId['iccid'] = res.data.simProfileVo.iccid;
        }
        this.props.dispatch({
          type: 'vehicleInfo/setVehicleInfo',
          payload: {
            ...deviceId,
          },
        }).then(() => {
          router.push({
            pathname: '/deviceManager/vehicleMngExtCompliant/vehicleInfoDetailExtCompliant',
            state: { module: '车辆管理' },
          });
        });
      },
    })

  };

  handleDetailIPDA = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipda/findById',
      payload: deviceId,
      callback: ipdaDetail => {
        if (ipdaDetail.statusCode === '0') {
          this.setState({ ipdaDetailModelData: ipdaDetail.data, ipdaDetailVisible: true });
        } else {
          message.error(ipdaDetail.statusMessage);
        }
      },
    });
  };

  handleTableChange = (value) => {
    const { vin } = this.state;
    const params = {
      vin,
      ...value,
    };
    // this.setState({
    //   pagination: { ...this.state.pagination, page: value.current, pageSize: value.pageSize },
    // });
    this.fetchData(params);
  };

  renderForm() {
    const { vin } = this.state;
    return (
      <Card bordered={false}>
        <Form
          layout="inline"
          ref={this.formRef}
          onFinish={this.handleSearch}
        >
          <Form.Item label="VIN号" name="vin"
            rules={[{
              required: true,
              message: '请至少输入6位数字或字母',
            },
            {
              min: 6,
              message: '请至少输入6位数字或字母',
            },]}>
            <Input
              placeholder="请输入VIN号"
              style={{ width: '300px', marginRight: '10px' }}
            />
          </Form.Item>
          <Space size={5} style={{ marginLeft: 'auto' }}>
            <Form.Item>
              <Button type="primary" htmlType='submit' size='small'>
                查询
              </Button>
            </Form.Item>
            <Form.Item>
              <Button size='small' onClick={this.handleReset}>
                重置
              </Button>
            </Form.Item>
          </Space>
        </Form>
      </Card>
    );
  }

  render() {
    const {
      data,
      formValues,
      detailDisable,
      qualityUserOptions,
      phoneMap,
      pagination,
      loading,
    } = this.state;

    const { menu: { permissions } } = this.props;
    const { location: { pathname } } = this.props;
    const isDetail = permissions.includes(pathname + '/' + 'vehicleMngExtCompliant-show');

    const { dispatch } = this.props;


    const columns = [
      {
        title: 'VIN号',
        dataIndex: 'vin',
        render: (text, record) => {
          if (isDetail) {
            return <a onClick={() => this.handleDetailVIN(record)}>{text}</a>;
          } else {
            return text;
          }
        },
      },
      {
        title: '品牌',
        dataIndex: 'brandId',
        render: text => {
          if (text) {
            return getDicByKey(this.context.dicData, 'optBrand', text) || text;
          } else {
            return text;
          }
        },
      },
      {
        title: '车系',
        dataIndex: 'seriesId',
        render: text => {
          if (text) {
            return getDataByCode(this.state.redisData, 'vehicleSeriesList', text) || text;
          } else {
            return text;
          }
        },
      },
      {
        title: '车型',
        dataIndex: 'styleId',
        render: text => {
          if (text) {
            return getDataByCode(this.state.redisData, 'vehicleTypeList', text) || text;
          } else {
            return text;
          }
        },
      },
      {
        title: '颜色',
        dataIndex: 'colorName',
      },
      {
        title: '经销商',
        dataIndex: 'dealerId',
        render: text => {
          if (text) {
            return getDataByCode(this.state.redisData, 'dealerList', text) || text;
          } else {
            return text;
          }
        },
      },
      {
        title: '网联类型',
        dataIndex: 'carSpt',
        render: (text) => {
          return text === '1' ? '手机' : '传统';
        },
      },
      {
        title: '集团企业',
        dataIndex: 'groupId',
        render: (text, record) => {
          if (text && record.vhlType === 7) {
            const {
              qualityTest: { options },
            } = this.props; // 集团编码关系
            const option = options.filter(item => item.value === text);
            return option.length > 0 ? option[0].label : text;
          } else return null;
        },
      },
      {
        title: '类型',
        dataIndex: 'vhlType',
        render: text => {
          if (text || text === 0) {
            return typeMap.get(text) ? typeMap.get(text) : text;
          } else {
            return text;
          }
        },
      },
      {
        title: '激活状态',
        dataIndex: 'enrollStatus',
        render: (text, record) => {
          // 如果状态码为0 并且 remark等于“等待app激活” 就显示remark的值
          if (text === 0 && record.remarks === '等待app激活') {
            return record.remarks;
          }
          // 状态码有值 并且在 enrollMap 可以查到就显示对应的值 否则 显示空
          return (text || text === 0) && enrollMap.get(text) ? enrollMap.get(text) : '';

        },
      },
      {
        title: '实名认证状态',
        dataIndex: 'realNameStatus',
        render: (text, record) => {
          if (
            record.vhlType === 3 ||
            record.vhlType === 4 ||
            record.vhlType === 5 ||
            record.vhlType === 6
          ) {
            return '';
          } else {
            if (text) {
              return realMap.get(text) ? realMap.get(text) : text;
            } else {
              return text;
            }
          }
        },
      },
      {
        title: '备注',
        dataIndex: 'remarks',
        render: (text, record) => {
          if (record.enrollStatus === 5 || record.realNameStatus === '3') {
            return (
              <span style={{ color: 'red' }}>
                <Ellipsis length={10} tooltip>
                  {text}
                </Ellipsis>
              </span>
            );
          } else {
            return '';
          }
        },
      },
      {
        title: '入库时间',
        dataIndex: 'createDate',
        render: text => {
          return text;
        },
      },
      {
        title: '车机',
        dataIndex: 'pdsn',
        render: text => {
          if (detailDisable) {
            return text;
          } else {
            return <a onClick={() => this.handleDetailIPDA(text)}>{text}</a>;
          }
        },
      },
      {
        title: 'TBOX',
        dataIndex: 'tbox',
        render: text => {
          if (detailDisable) {
            return text;
          } else {
            return <a onClick={() => this.handleDetailTbox(text)}>{text}</a>;
          }
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: pagination?.total,
      current: pagination?.page,
      pageSize: pagination?.pageSize,
      showTotal: () => (
        <span>共&nbsp;{!has(pagination, 'total') ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    return (
      <PageHeaderLayout>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <Card style={{ marginTop: 12 }}>
            <Table
              style={{ marginTop: 12 }}
              size={'small'}
              loading={loading}
              dataSource={data}
              columns={columns}
              scroll={{ x: 'max-content' }}
              pagination={paginationProps}
              onChange={this.handleTableChange}
            />
          </Card>
          <TboxDetailModal
            changeVisible={() =>
              this.setState({ tboxDetailVisible: false, tboxDetailModelData: {} })
            }
            visible={this.state.tboxDetailVisible}
            detailModelData={this.state.tboxDetailModelData}
            dispatch={dispatch}
          />
          <IPDADetailModal
            changeVisible={() =>
              this.setState({ ipdaDetailVisible: false, ipdaDetailModelData: {} })
            }
            visible={this.state.ipdaDetailVisible}
            detailModelData={this.state.ipdaDetailModelData}
            dispatch={dispatch}
          />
        </div>
      </PageHeaderLayout>
    );
  }
}

export default connect(state => {
  return {
    currentUser: state.user2.currentUser,
    qualityTest: state.qualityTest,
    extendForm: state.extendForm,
    menu: state.menu,
    vehicleInfo: state.vehicleInfo,
  };
})(VehicleList);
